//
//  PKDownLoad.m
//  PianKe
//
//  Created by ybq on 16/1/5.
//  Copyright © 2016年 B7_Young. All rights reserved.
//

#import "PKDownLoad.h"
@interface PKDownLoad () <NSURLSessionDownloadDelegate>

@end

@implementation PKDownLoad

- (instancetype)initWithModel:(PKRadioDetailModel *)model {
    self = [super init];
    if (self) {
        // 在初始化下载类的时候,创建出来下载所需的NSURLSession,让Session去执行一个下载的任务,我们用一个DownLoadTask去保存这个下载任务,方便对它进行控制
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue currentQueue]];
        _downLoadTask = [_session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.musicUrl]]];
        _model = model;
        [_downLoadTask resume];
        _isDownLoading = YES;
    }
    return self;
}

// 下载完成后执行的方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // 下载完成之后,把下载好的歌曲存到一张表里面,当访问已下载页面时可以从这个表里面读取数据,显示在已下载界面
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    // 获取当前下载的进度和总进度
    _totalBytesWritten = totalBytesWritten;
    _totalBytesExpectedToWriten = totalBytesExpectedToWrite;
}

- (void)pauseDownLoad {
    [_downLoadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        // 暂停下载之后保存下载了一半的data(用属性保存)
        _data = resumeData;
    }];
    _isDownLoading = NO;
}

- (void)continueDownLoad {
    // 继续下载
    _downLoadTask = [_session downloadTaskWithResumeData:_data];
    [_downLoadTask resume];
    _isDownLoading = YES;
}

@end
